//
//  PYCandidates.m
//  cocoa_py
//
//  Created by qiaolun on 6/29/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "PYCandidates.h"


@implementation PYCandidates

- (id) initWithContentRect: (NSRect) contentRect
                 styleMask: (unsigned int) aStyle
                   backing: (NSBackingStoreType) bufferingType
                     defer: (BOOL) flag
{
    if (self = [super initWithContentRect: contentRect
                                styleMask: NSBorderlessWindowMask
                                  backing: bufferingType
                                    defer: flag])
		
    {
		[self setOpaque:NO]; // Needed so we can see through it when we have clear stuff on top
		[self setHasShadow: YES];
		[self setLevel:NSFloatingWindowLevel]; // Let's make it sit on top of everything else
		[self setAlphaValue:0.9f]; // It'll start out mostly transparent
		
		NSRect frame = [self frame];
		_view = [[NSTextView alloc] initWithFrame:frame];
		
		
    }
    return self;
}

- (void) awakeFromNib {
	_fontHeight = 20.0;
	
	[_view setFont:[NSFont userFontOfSize:16.0]];
	[_view setTextColor:[NSColor whiteColor]];
	[_view setBackgroundColor:[NSColor blueColor]];
	
	[_view setString:@"cocoa pinyin $Id$"];
	[self setContentView:_view];
	
	const float LargeNumberForText = 1.0e7;
	
	NSScrollView *scrollView = [_view enclosingScrollView];
	[scrollView setHasVerticalScroller:YES];
	[scrollView setHasHorizontalScroller:YES];
	[scrollView setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];
	
	NSTextContainer *textContainer = [_view textContainer];
	[textContainer setContainerSize:NSMakeSize(LargeNumberForText, LargeNumberForText)];
	[textContainer setWidthTracksTextView:NO];
	[textContainer setHeightTracksTextView:NO];
	
	[_view setMaxSize:NSMakeSize(LargeNumberForText, LargeNumberForText)];
	[_view setHorizontallyResizable:YES];
	[_view setVerticallyResizable:YES];
	[_view setAutoresizingMask:NSViewNotSizable];
	
	
	[self hide:nil];
}

- (NSSize)contentSize
{
	NSLayoutManager *layoutManager = [_view layoutManager];
	NSTextContainer *textContainer = [_view textContainer];
	
	[layoutManager boundingRectForGlyphRange:NSMakeRange(0, [layoutManager numberOfGlyphs]) inTextContainer:textContainer]; // dummy call to force layout
	
	return [[_view layoutManager] usedRectForTextContainer:[_view textContainer]].size;
}


- (NSPoint)estimatePoint:(NSPoint)point rect:(NSRect)rect
{
	NSRect frameRect = [self frame];
	
	if (point.x < NSMinX(rect))
		point.x = NSMinX(rect);
	if (point.x + frameRect.size.width> NSMaxX(rect))
		point.x = NSMaxX(rect) - frameRect.size.width;
	
	if (point.y < NSMinY(rect))
		point.y = NSMinY(rect) - frameRect.size.height;
	else if ((point.y - frameRect.size.height) < NSMinY(rect))
		point.y += _fontHeight + 5;
	else
		point.y -= frameRect.size.height;
	
	return point;
}



- (NSPoint)_fixCaretPosition:(NSPoint)caretPosition
{
	NSRect frame = [[NSScreen mainScreen] frame];
	BOOL hasFocus = NO;
	
	NSArray *screens = [NSScreen screens];
	NSEnumerator *enumerator = [screens objectEnumerator];
	NSScreen *screen;
	
	if ([screens count] < 2) {
		screen = [NSScreen mainScreen];
		frame = [screen visibleFrame];
		caretPosition = [self estimatePoint:caretPosition rect:frame];
		return caretPosition;
	}
	
	while (screen = [enumerator nextObject]) {
		NSRect screenFrame = [screen frame];
		
		if (!hasFocus && caretPosition.x >= NSMinX(screenFrame) && caretPosition.x <= NSMaxX(screenFrame)) {
			frame = [screen visibleFrame];
			hasFocus = YES;
			break;
		}
	}
	
	if (hasFocus) {
		caretPosition = [self estimatePoint:caretPosition rect:frame];
		return caretPosition;
	}
	
	NSPoint point;
	point.x = (int)(frame.size.width / 2.0);
	point.y = (int)(frame.size.height / 2.0);
	return point;
}

- (void)setCandidateWindowOrigin:(NSPoint)origin
{
	[self setFrameOrigin:origin];
}

- (void)adjustSize {
	
	NSSize size = [self contentSize];
	NSPoint origin = [self frame].origin;
	
	NSRect rect = NSMakeRect(origin.x, origin.y, size.width + 10.0, size.height + 0.0);
	[self setFrame:rect display:TRUE];
	
}

- (void)showCandidates:(NSArray *)candidates client:(id)sender {

	
	// set text
	if(candidates == nil){
		[self hide:sender];
		return;
	} else if([candidates count] > 0){
		NSMutableString *buff = [NSMutableString stringWithCapacity:50];
		[buff appendString:@" "];
		for(int i = 0; i < [candidates count]; i++){
			[buff appendFormat:@"%d.%@ ", i+1, [candidates objectAtIndex:i]];
		}
		[_view setString:buff];
		[_view setNeedsDisplay:YES];
		[_view setFrameOrigin:NSMakePoint(0.0, 0.0)];
		// NSLog(@"showcandidates %@", buff);
	} else {
		[self hide:sender];
		return;
	}
	
	// update cursor position
	NSPoint caretPosition;
	NSRect lineHeightRect;
	[sender attributesForCharacterIndex:0 lineHeightRectangle:&lineHeightRect];
	
	
	// TO DO: set font metrics
	caretPosition = [self _fixCaretPosition:lineHeightRect.origin];
	[self setCandidateWindowOrigin:caretPosition];

	// [];
	[self adjustSize];

	
	if(![self isVisible]){
		[self orderFront:sender];
	}
	
}

- (void)hide:(id)sender {
	if([self isVisible]){
		[self orderOut:sender];
	}
}

- (void)dealloc {

	[_view release];
	
	[super dealloc];
}

@end
